package org.xkx.demo.netty.hello.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

public class HelloClientHandler extends ChannelInboundHandlerAdapter {
	private ByteBuf firstMsg;

	public HelloClientHandler() {
		String msg = "你好服务端！";
		System.out.println("发送的消息：" + msg);
		byte[] req = msg.getBytes(Charset.forName("UTF-8"));
		firstMsg = Unpooled.buffer(req.length);
		firstMsg.writeBytes(req);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(firstMsg);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String str = new String(bytes);
		System.out.println("接收的消息：" + str);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		super.exceptionCaught(ctx, cause);
	}
}
